package com.education.welco.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.education.common.pojo.SysAppUser;
import com.education.common.pojo.TStudent;
import com.education.common.utils.ApiReturnObject;
import com.education.common.utils.DateUtil;
import com.education.common.utils.StringUtils;
import com.education.welco.enums.ResourceTypeEnums;
import com.education.welco.feign.MsgClient;
import com.education.welco.feign.userFeign;
import com.education.welco.mapper.ForAppTeacherMapper;
import com.education.welco.mapper.PlatformResourcesMapper;
import com.education.welco.pojo.*;
import com.education.welco.pojo.dto.ForAppTeacherDTO;
import com.education.welco.pojo.vo.*;
import com.education.welco.service.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.education.common.utils.DateUtil.YYYYMMDDHHMMSS;
import static com.education.welco.pojo.consts.FileConst.*;

/**
 * 教师端app相关接口
 */
@Service
public class AppTeacherServiceImpl implements IAppTeacherService {

    @Autowired
    private ISTheoryClassroomService sTheoryClassroomService;
    @Autowired
    private ISCatalogClassTeaService catalogClassTeaService; //在授班级
    @Autowired
    private ISCatalogMenuService catalogMenuService;
    @Autowired
    private ISResourcesService resourcesService;
    @Autowired
    private ISResourceClassService resourceClassService;
    @Autowired
    private ISCatalogWorkService catalogWorkService;
    @Autowired
    private ISHomewordClassService homewordClassService;
    @Autowired
    private ISAnsweringService answeringService;
    @Autowired
    private ISQueansClassService queansClassService;
    @Autowired
    private ISTheoryPartekeService isTheoryPartekeService;//参与教授中间表
    @Autowired
    private ITClassService classService;
    @Autowired
    private userFeign userFeign;
    @Autowired
    private MsgClient msgClient;
    @Autowired
    private ITStudentService studentService;
    @Autowired
    private ForAppTeacherMapper forAppTeacherMapper;
    @Autowired
    private ITTeacherService teacherService;
    @Autowired
    private IPlatResourceShareService platResourceShareService;
    @Autowired
    private IPlatformResourcesService platformResourcesService;
    @Autowired
    private IUserStarService userStarService;
    @Autowired
    private PlatformResourcesMapper platformResourcesMapper;
    @Autowired
    private IMineResCatalogService mineResCatalogService;
    @Autowired
    private IMineResTableService mineResTableService;

    private static final DecimalFormat df = new DecimalFormat("0.00");

    /**
     * 查询排课信息
     *
     * @param dto
     * @return
     */
    @Override
    public Map<String, Object> selectPaikeList(ForAppTeacherDTO dto) {
        Map<String, Object> allMap = new HashMap<>();
        buildTime(dto);
        List<STheoryClassroomVO> list = forAppTeacherMapper.selectPaikeList(dto);
        List<STheoryClassroomVO> ingList = new ArrayList<>();
        Date date = new Date();
        Iterator<STheoryClassroomVO> it = list.iterator();
        while (it.hasNext()) {
            STheoryClassroomVO vo = it.next();
            Date attendTime = vo.getAttendTime();
            Date endTime = vo.getEndTime();
            Date format = DateUtil.format(vo.getDateFormat(), "yyyy-MM-dd");
            String dateString = DateUtil.dateToStringTwo(format, "yyyy年MM月dd日 EEEE");
            if (date.before(attendTime)) {
                vo.setTeachingStatus("未开始");
            } else if (date.after(attendTime) && date.before(endTime)) {
                vo.setTeachingStatus("授课中");
                ingList.add(vo);
                it.remove();
            } else if (date.after(endTime)) {
                vo.setTeachingStatus("课程结束");
            }
            vo.setDateFormat(dateString);
        }
        Map<String, List<STheoryClassroomVO>> map = list.stream().collect(Collectors.groupingBy(STheoryClassroomVO::getDateFormat));
        List<STheoryClassroomDayVO> voList = new ArrayList<STheoryClassroomDayVO>();
        for (String key : map.keySet()) {
            voList.add(new STheoryClassroomDayVO(key, map.get(key)));
        }
        allMap.put("ingList", CollectionUtil.isEmpty(ingList) ? new STheoryClassroomVO() : ingList.get(0));
        allMap.put("dataList", voList);
        return allMap;
    }

    /**
     * 新增排课
     *
     * @param sTheoryClassroom
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiReturnObject insertSTheoryClassroom(STheoryClassroom sTheoryClassroom) throws Exception {

        if (sTheoryClassroom.getClassroomId() != null && sTheoryClassroom.getAttendTime() != null && sTheoryClassroom.getEndTime() != null) {
            //将字符串日期转换为日期类型
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            long between = (sTheoryClassroom.getEndTime().getTime() - sTheoryClassroom.getAttendTime().getTime()) / 1000;//除以1000是为了转换成秒
            long hour1 = between % (24 * 3600) / 3600;
            long minute1 = between % 3600 / 60;
            sTheoryClassroom.setClassHours(hour1 + "小时" + minute1 + "分钟");
            sTheoryClassroom.setId(null);
            //往数据库添加数据
            sTheoryClassroomService.insertSTheoryClassroom(sTheoryClassroom);

            //获取添加的数据生成的主键
            Integer id = sTheoryClassroom.getId();
            //预约课程时选择了参与老师
            if (sTheoryClassroom.getTeaIdList() != null && sTheoryClassroom.getTeaIdList().size() > 0) {
                //获取当前登录人的姓名
                Map<String, Object> map = userFeign.findByUserId(sTheoryClassroom.getUserId());
                //给被选择的老师发布消息   谁邀请的    什么课 开始时间    结束时间
                String content = map.get("name") + "老师邀请您参加" + sTheoryClassroom.getClassroomName() + "课程," +
                        "上课时间为:" + sTheoryClassroom.getAttendTimeString() + "-" + sTheoryClassroom.getEndTimeString();
                String title = "课堂邀请";
                //消息内容   消息标题   消息类型    邀请老师id集合
                msgClient.addSysInfoMsg(title, content, "1", sTheoryClassroom.getTeaIdList(), sTheoryClassroom.getUserId());
                //往中间表添加数据
                STheoryParteke sTheoryParteke = new STheoryParteke();
                //设置课堂id
                sTheoryParteke.setTheoryId(id);
                for (Integer integer : sTheoryClassroom.getTeaIdList()) {
                    sTheoryParteke.setUserId(integer);
                    //中间表加入数据
                    isTheoryPartekeService.insertSTheoryParteke(sTheoryParteke);
                }
            }

            return new ApiReturnObject("200", "添加成功", "");
        } else {
            return new ApiReturnObject("201", "缺少参数", "");
        }
    }

    //查询目录列表
    public SCatalogMenu listSon2(SCatalogMenu cList) {
        //根据第一级的id查询出下级列表
        List<SCatalogMenu> jrCatalogs = catalogMenuService.selectSCatalogMenuByParentId(cList.getId());
        if (jrCatalogs != null && jrCatalogs.size() > 0) {
            //设置子级集合
            cList.setChildren(listSon(jrCatalogs));
        }
        return cList;
    }

    //查询目录列表
    public List<SCatalogMenu> listSon(List<SCatalogMenu> cList) {
        for (SCatalogMenu catalogMenu : cList) {
            //根据第一级的id查询出下级列表
            List<SCatalogMenu> jrCatalogs = catalogMenuService.selectSCatalogMenuByParentId(catalogMenu.getId());
            if (jrCatalogs != null && jrCatalogs.size() > 0) {
                //设置子级集合
                catalogMenu.setChildren(listSon(jrCatalogs));
            }
        }
        return cList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void testTransActional() throws Exception {
//        sCatalogMenuMapper.insetTest();
        if (1 == 1) {
            throw new Exception("事务出错");
        }
//        sCatalogMenuMapper.insetTest2();
    }

    /**
     * 课堂详情-课程目录
     *
     * @param sCatalogMenu
     * @return
     */
    @Override
    public ApiReturnObject selectSCatalogMenuList(SCatalogMenu sCatalogMenu) {
        SCatalogMenuVo list = catalogMenuService.selectSCatalogMenuList22(sCatalogMenu);
        //2级 以及 下面子列表
        SCatalogMenuVo sCatalogMenus = listSonOne(list);
        if (sCatalogMenus.getChildren() == null) {
            return new ApiReturnObject("202", "暂无教学大纲，请先编辑教学大纲", "");
        }
        //加入资源列表
        selectSResourcesList(sCatalogMenus);
        return new ApiReturnObject("200", "查询成功", sCatalogMenus.getChildren());
    }

    //课程资源详情
    public void selectSResourcesList(SCatalogMenuVo vo) {
        List<SCatalogMenuVo> children = vo.getChildren();
        buildSResourcesList(children);
    }

    public void buildSResourcesList(List<SCatalogMenuVo> children) {
        for (SCatalogMenuVo child : children) {
            List<SResources> sResourceList = forAppTeacherMapper.selectSResourcesList(child.getId());
            child.setSResourceList(jxResource(sResourceList));
            List<SCatalogMenuVo> children1 = child.getChildren();
            if (CollectionUtil.isNotEmpty(children1)) {
                buildSResourcesList(children1);
            }
        }
    }

    public List<SResources> jxResource(List<SResources> sResourceList) {
        if (sResourceList != null && sResourceList.size() > 0) {
            //格式化创建时间
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //list遍历
            for (SResources sResource : sResourceList) {
                //对资源名称做操作
                if (sResource.getRUrl() != null && !"".equals(sResource.getRUrl())) {
                    //后缀suffix
                    String[] split = sResource.getRUrl().split("\\.");
                    String suffix = split[split.length - 1];
                    if (suffix.contains(",")) {
                        suffix = suffix.split(",")[0];
                    }
                    //名字拼接文件后缀名
                    sResource.setRName(sResource.getRName() + "." + suffix);
                }
                String type = sResource.getType();
                //格式化时间
                String format = simpleDateFormat.format(sResource.getCreateTime());
                sResource.setCreateTimeString(format);
                sResource.setTypeString(ResourceTypeEnums.getDesc(type));
            }
        }
        return sResourceList;
    }
//    @Override
//    public ApiReturnObject selectSResourcesList(SResources resources) {
//        //资源的分类    资源类型  1 教学课件  2 技术文档  3 教学笔记 4 图片 5 视频  6 3D 7 flash   根据类型查询出对应的资源
//        //查询服务调用
//        List<SResources> sResourceList = resourcesService.selectSResourcesList(resources);
//        //处理查询结果
//        if (sResourceList != null && sResourceList.size() > 0) {
//            //格式化创建时间
//            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            //list遍历
//            for (SResources sResource : sResourceList) {
//                //对资源名称做操作
//                if (sResource.getRUrl() != null && !"".equals(sResource.getRUrl())) {
//                    //后缀suffix
//                    String suffix = sResource.getRUrl().split("\\.")[1];
//                    if (suffix.contains(",")) {
//                        suffix = suffix.split(",")[0];
//                    }
//                    //名字拼接文件后缀名
//                    sResource.setRName(sResource.getRName() + "." + suffix);
//                }
//                String type = sResource.getType();
//                //格式化时间
//                String format = simpleDateFormat.format(sResource.getCreateTime());
//                sResource.setCreateTimeString(format);
//                sResource.setTypeString(ResourceTypeEnums.getDesc(type));
//            }
//        }
//        return new ApiReturnObject("200", "查询成功", sResourceList);
//    }

    @Override
    public List<TClass> selectClassListByTeaId(TClass tClass) {
        //根据老师id查找老师所代课的班级
        List<TClass> tClasses = classService.selectClassListByTeaId(tClass);
        for (TClass aClass : tClasses) {
            //格式化创建时间
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateString = formatter.format(aClass.getCreateTime());
            aClass.setCreateTimeStr(dateString);
        }
        return tClasses;
    }

    /**
     * 查询学生列表
     *
     * @param student
     * @return
     */
    @Override
    public List<TStudent> selectStudentList(TStudent student) {
        List<String> classIdList = forAppTeacherMapper.getTeacherClassId(student.getTeacherId());
        List<TStudent> list = forAppTeacherMapper.selectTStudentList(student, classIdList);
//        for (TStudent tStudent : list) {
//            String desc = StudentStateEnums.getDesc(tStudent.getApplicationStatus());
//            tStudent.setApplicationStatus(desc);
//        }
        return list;
    }

    /**
     * 修改学生信息
     *
     * @param student
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateStuByTea(TStudent student) throws Exception {
        Integer userId = student.getUserId();
        Integer classId = student.getClassId();
        userFeign.updateStuPC(userId, classId);
        studentService.updateTStudent(student);
    }

    @Override
    public ApiReturnObject addStuByTea(TStudent student) {
        TStudent tStudent = new TStudent();
        //根据手机号判断是否存在
        if (!"".equals(student.getPhone())) {
            tStudent.setPhone(student.getPhone());
            List<TStudent> tStudents = studentService.selectTStudentList(tStudent);
            if (tStudents.size() > 0) {
                return new ApiReturnObject("201", "该手机号已存在", "");
            }
        }
        //根据身份证判断是否存在
        tStudent.setPhone("");
        if (StringUtils.isNotBlank(student.getIdcardno())) {
            tStudent.setIdcardno(student.getIdcardno());
            List<TStudent> tStudents = studentService.selectTStudentList(tStudent);
            if (tStudents.size() > 0) {
                return new ApiReturnObject("201", "该身份证号已存在", "");
            }
        }
        //设置班级id
        //if (student.getClassIdList() != null && student.getClassIdList().size() > 1) {
        //    student.setClassId(student.getClassIdList().get(1));
        //}

        SysAppUser appUser = new SysAppUser();
        appUser.setClassId(student.getClassId());
        appUser.setSchoolId(student.getSchoolId());
        appUser.setSysPhone(student.getPhone());
        appUser.setIdcardno(student.getIdcardno());
        appUser.setCreateTime(new Date());
        appUser.setSysRelname(student.getStudentName());

        int id;
        boolean bool = userFeign.findUserBySchoolId2(student.getPhone());
        if (bool) {
            //账号存在不新增
            /* return new ApiReturnObject("201","该手机号已存在","");*/
            //查询已存在的用户id与学生表建立关联关系
            ApiReturnObject sysUserBysysPhone = userFeign.findSysUserBysysPhone(student.getPhone());
            id = (int) sysUserBysysPhone.getReturnObject();
            //用户表对应用户添加学校id和班级id以及用户类型
            studentService.updateInfoForUser(student.getUserId(), student.getClassId(), student.getSchoolId(), 1, 2);
        } else {
            //账号不存在新增
            ApiReturnObject apiReturnObject = userFeign.addAppUser3(student.getPhone(), student.getClassId().toString(), student.getSchoolId(),
                    student.getIdcardno(), student.getStudentName(), 1);
            id = (int) apiReturnObject.getReturnObject();
        }
        student.setUserId(id);
        student.setApplicationStatus("1");
        studentService.insertTStudent(student);
        return new ApiReturnObject("200", "添加成功", "");
    }

    @Override
    public ApiReturnObject pasrejbytea(TStudent student) {
        int i = studentService.updateTStudent(student);
        //此处的state  1通过2驳回
        if (student.getApplicationStatus().equals("1")) {
            return new ApiReturnObject("200", "通过成功!", "");
        }
        return new ApiReturnObject("200", "驳回成功!", "");
    }

    @Override
    public ApiReturnObject del(TStudent student) {
        TStudent tStudent = studentService.selectTStudentById(student.getId());
        //通过查询到的学生用户id修改用户表的系统状态 用户状态（0正常，1删除，2黑名单，3已登录）
        if (tStudent.getUserId() != null) {
            userFeign.updateByUserId(tStudent.getUserId());   //1删除
        }
        if (student.getId() != null) {
            //删除app用户
            //删除学生
            studentService.deleteTStudentById(student.getId());
            return new ApiReturnObject("200", "删除成功", "");
        }
        return new ApiReturnObject("201", "缺少id参数", "");
    }

    @Override
    public ApiReturnObject deptAndTeaList(TTeacher tTeacher) {
        if (tTeacher != null) {

            List<TTeacher> tTeachers = teacherService.selectTTeacherList(tTeacher);

            return new ApiReturnObject("200", "查询成功", tTeachers);
        }
        return new ApiReturnObject("201", "缺少schoolId", "");
    }

    @Override
    public ApiReturnObject sCatalogMenuList(SCatalogMenu catalogMenu) {
        //根据课程id 查询出 之下的目录
        if (catalogMenu.getUserId() != null) {
            //山西工程学校逻辑修改
            //根据用户id 查出学校id
            Map<String, Object> map = userFeign.findByUserId(catalogMenu.getUserId());
            Integer schoolId = (Integer) map.get("schoolId");
            if (schoolId == 109) {
                catalogMenu.setDeptId(schoolId);
                catalogMenu.setUserId(null);
            } else {
                //查询出备课列表
                catalogMenu.setUserId(catalogMenu.getUserId());
            }
            catalogMenu.setParentId(0);
            List<SCatalogMenu> list = catalogMenuService.selectSCatalogMenuListTwo(catalogMenu);
            //添加在授班级
//            List<SCatalogMenu> catalogMenuList = addClass(list);
            return new ApiReturnObject("200", "查询成功", list);
        } else {
            return new ApiReturnObject("201", "缺少userId参数", "");
        }
    }

    @Override
    public ApiReturnObject roomList(STheoryClassroom theoryClassroom) {
        List<TClass> cIdList = sTheoryClassroomService.selectSTheoryClassroomListByTimeAndIn(theoryClassroom);
        return new ApiReturnObject("200", "查询成功", cIdList);
    }

    @Override
    public ApiReturnObject shareSchResList(Integer schoolId, Integer teaId, String fileName,
                                           Integer pageNum, Integer pageSize, String orderBy) {
        if (StringUtils.isNotEmpty(fileName)) {
            //模糊查
            List<PlatformResources> platformResourcesList = platResourceShareService.selectShareSchoolResListBySchoolId(schoolId, teaId, null, null);
            List<String> ridCollect = platformResourcesList.stream().map(platformResources -> platformResources.getId()).collect(Collectors.toList());
            List<PlatformResources> platResourceShareList = selectShareSchoolResListBySchoolIdAndFileName(teaId, ridCollect, fileName, null, null, pageNum, pageSize, orderBy);
            for (PlatformResources platformResources : platResourceShareList) {
                platformResources.setFileSize(df.format((float) Integer.valueOf(platformResources.getFileSize()) / 1024));
                platformResources.setResType(judgeResType(platformResources.getExtension()));
            }
            PageInfo<PlatformResources> platformResourcesPageInfo = new PageInfo<PlatformResources>(platResourceShareList);
            return new ApiReturnObject("200", "查询成功！", platformResourcesPageInfo);
        } else {
            //没条件
            if (pageNum != null && pageSize != null) {
                PageHelper.startPage(pageNum, pageSize);
            }
            List<PlatformResources> platResourceShareList = forAppTeacherMapper.selectShareSchoolResListBySchoolId(schoolId, teaId, orderBy);
            for (PlatformResources platformResources : platResourceShareList) {
                platformResources.setFileSize(df.format((float) Integer.valueOf(platformResources.getFileSize()) / 1024));
                platformResources.setResType(judgeResType(platformResources.getExtension()));
            }
            PageInfo<PlatformResources> platformResourcesPageInfo = new PageInfo<PlatformResources>(platResourceShareList);
            return new ApiReturnObject("200", "查询成功！", platformResourcesPageInfo);
        }
    }

    //根据文件后缀判断资源类型
    public String judgeResType(String extension) {
        //        1
        if (IMG_FILE.contains(extension)) return "1";
        //        2
        if (VIDEO_FILE.contains(extension)) return "2";
        //        3
        if (DOC_FILE.contains(extension)) return "3";
        return "0";
    }

    private List<PlatformResources> selectShareSchoolResListBySchoolIdAndFileName(Integer teaId, List<String> ridCollect,
                                                                                  String fileName, Set<String> extensionSet,
                                                                                  Boolean inOrNot, Integer pageNum,
                                                                                  Integer pageSize, String orderBy) {
        //父子级别
        if (ridCollect != null && ridCollect.size() == 0) {
            return null;
        }
        List<PlatformResources> childrenList = platformResourcesService.getChildrenList(ridCollect, false);
        List<String> ridALLCollect = childrenList.stream().map(platformResources -> platformResources.getId()).collect(Collectors.toList());
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        return forAppTeacherMapper.selectShareSchoolResListBySchoolIdAndFileName(teaId, ridALLCollect, fileName, extensionSet, inOrNot, orderBy);
    }

    @Override
    public ApiReturnObject listDir(String pid, Long userId, Integer pageNum, Integer pageSize, String fileName) {
        PageInfo<PlatformResources> fileListPage = listTheDir(userId, pid, pageNum, pageSize, fileName);
        for (PlatformResources platformResources : fileListPage.getList()) {
            platformResources.setResType(judgeResType(platformResources.getExtension()));
        }
        return new ApiReturnObject("200", "目录文件查询成功！", fileListPage);
    }

    public PageInfo<PlatformResources> listTheDir(Long userId, String pid, Integer pageNum, Integer pageSize, String fileName) {
        PlatformResources platformResources = new PlatformResources();
        platformResources.setUserId(userId);
        platformResources.setPid(pid);
        if (StringUtils.isNotBlank(fileName) && !fileName.equals("null")) {
            platformResources.setFileName(fileName);
        }
        PageHelper.startPage(pageNum, pageSize);
        List<PlatformResources> platformResourcesList = platformResourcesMapper.selectPlatformResourcesListForListDir(platformResources);
        PageInfo<PlatformResources> platformResourcesPageInfo = new PageInfo<>(platformResourcesList);
        return platformResourcesPageInfo;
    }

    @Override
    public ApiReturnObject addStar(String resId, Integer userId) {
        UserStarVo userStarVo = new UserStarVo();
        userStarVo.setResId(resId);
        userStarVo.setUserId(userId);
        //检查用户是否之前存在
        UserStar userStar = userStarService.selectUserStarByResIdAndUserId(userStarVo.getResId(), userStarVo.getUserId());
        //存在走修改状态业务
        if (Objects.nonNull(userStar)) {
            UserStar userStarcp = new UserStar();
            userStarcp.setResId(userStar.getResId());
            userStarcp.setUserId(userStar.getUserId());
            userStarcp.setIsDelete(false);
            userStarService.updateUserStarByResIdAndUserId(userStarcp);
            //状态判定
            if (userStar.getIsDelete()) {
                return new ApiReturnObject("星标成功！", 1);
            }
            return new ApiReturnObject("取消星标成功！", 0);
        }
        //不存在走新增业务
        userStarService.insertUserStar(userStarVo);
        return new ApiReturnObject("星标成功！", 1);
    }

    @Override
    public ApiReturnObject queryLeftMenuByTeaIdAndType(Integer teaId, Integer type) {
        List<MineResCatalogVO> result = mineResCatalogService.queryLeftMenuByTeaIdAndType(teaId, type);
        return new ApiReturnObject("200", "查询成功！", result);
    }

    @Override
    public ApiReturnObject queryAllResListByTeaIdAndType(Integer teaId, Integer type, String resName,
                                                         Integer pageNum, Integer pageSize) {
        MineResCatalog mineResCatalog = new MineResCatalog();
        mineResCatalog.setCreateId(teaId);
        mineResCatalog.setCatalogType(String.valueOf(type));
        List<MineResCatalog> mineResCatalogVOList = mineResCatalogService.selectMineResCatalogList(mineResCatalog);
        List<Integer> catalogIdList = mineResCatalogVOList.parallelStream().map(mineResCatalogVO -> mineResCatalogVO.getCatalogId()).collect(Collectors.toList());
        if (catalogIdList != null && catalogIdList.size() == 0)
            return new ApiReturnObject("200", "查询成功！", new PageInfo<MineResTable>(new ArrayList<>()));
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<MineResTable> result = mineResTableService.queryAllResListByTeaIdAndType(catalogIdList, resName, null, type);
        PageInfo<MineResTable> mineResTablePageInfo = new PageInfo<>(result);
        return new ApiReturnObject("200", "查询成功！", mineResTablePageInfo);
    }

    @Override
    public ApiReturnObject queryResListByCatalogId(Integer catalogId, String resName, Integer pageNum,
                                                   Integer pageSize, String orderBy, Integer resType) {
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<MineResTable> result = forAppTeacherMapper.queryResListByCatalogId(catalogId, resName, orderBy, resType);
        PageInfo<MineResTable> mineResTablePageInfo = new PageInfo<>(result);
        return new ApiReturnObject("200", "查询成功", mineResTablePageInfo);
    }

    @Override
    public ApiReturnObject updateResourceName(Integer mineResId, String mineResName) {
//        MineResCatalog mineResCatalog = new MineResCatalog();
//        mineResCatalog.setCatalogId(catalogId);
//        mineResCatalog.setCatalogName(catalogName);
//        mineResCatalogService.updateMineResCatalog(mineResCatalog);
        MineResTable mineResTable = new MineResTable();
        mineResTable.setMineResId(mineResId);
        mineResTable.setMineResName(mineResName);
        mineResTableService.updateMineResTable(mineResTable);
        return new ApiReturnObject("200", "修改成功", "修改成功");
    }

    @Override
    public ApiReturnObject recycleList(Integer teaId, Integer type, String resName, String orderBy, Integer pageNum, Integer pageSize) {
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
//        List<MineResTable> list = mineResTableService.selectMineResTableRecycleList(teaId, type, resName, orderBy);
        List<MineResTableAppVO> list = forAppTeacherMapper.selectMineResTableRecycleList(teaId, type, resName, orderBy);
        buildParentCatalogue(list);
        PageInfo<MineResTableAppVO> mineResTablePageInfo = new PageInfo<>(list);
        return new ApiReturnObject(mineResTablePageInfo);
    }

    @Override
    public ApiReturnObject oneClickClear(Integer teaUserId) {
        //查询回收站所有信息mine_res_table
        List<Integer> list = forAppTeacherMapper.selectClearList(teaUserId);
        if (CollectionUtil.isNotEmpty(list)) {
            forAppTeacherMapper.oneClickClear(list);
        }
        return new ApiReturnObject("200", "清空成功！", "清空成功！");
    }

    @Override
    public ApiReturnObject agreement(Integer userId, String aType) {
        String desc = forAppTeacherMapper.getAgreement(aType);
        return new ApiReturnObject("200", desc, desc);
    }

    private void buildParentCatalogue(List<MineResTableAppVO> list) {
        for (MineResTableAppVO vo : list) {
            buildParentCatalogue(vo, vo.getCatalogId());
        }
    }

    private void buildParentCatalogue(MineResTableAppVO vo, Integer catalogId) {
        MineResCatalogVO res = forAppTeacherMapper.getParentMeanu(catalogId);
        if (res != null) {
            String str = StringUtils.isBlank(vo.getParentCatalogue()) ? "" : vo.getParentCatalogue();
            vo.setParentCatalogue(str + "/" + res.getCatalogName());
            if (!res.getPid().equals(0)) {
                buildParentCatalogue(vo, res.getPid());
            }
        }
    }

    //查询课程一级目录
    public SCatalogMenuVo listSonOne(SCatalogMenuVo cList) {
        //根据课程id查询出一级目录
        List<SCatalogMenuVo> jrCatalogs = catalogMenuService.selectSCatalogMenuByParentId1(cList.getId());
        if (jrCatalogs != null && jrCatalogs.size() > 0) {
            //设置子级集合
            cList.setChildren(listSonTwo(jrCatalogs));
        }
        return cList;
    }

    //查询课程二级目录
    public List<SCatalogMenuVo> listSonTwo(List<SCatalogMenuVo> cList) {
        for (SCatalogMenuVo catalogMenu : cList) {
            //根据第一级的id查询出二级列表
            List<SCatalogMenuVo> jrCatalogs = catalogMenuService.selectSCatalogMenuByParentId1(catalogMenu.getId());
            if (jrCatalogs != null && jrCatalogs.size() > 0) {
                //设置子级集合
                catalogMenu.setChildren(listSonTwo(jrCatalogs));
            }
        }
        return cList;
    }

    //计算开始结束时间
    private void buildTime(ForAppTeacherDTO paramVo) {
        Integer dateType = paramVo.getDateType();
        String s = DateUtil.getdateFormatDbDate();
        Date endDate = DateUtil.format(s + " 23:59:59", YYYYMMDDHHMMSS);
        Date startDate = DateUtil.diffDate(endDate, dateType);
        paramVo.setStartDate(startDate);
        paramVo.setEndDate(endDate);
    }

}
